Page({
  data: {
    generatedNames: [],
    userInput: {},
    hasFavorites: false,
    favoriteCount: 0
  },

  onLoad() {
    // 从全局数据获取生成的名字和用户输入
    const app = getApp();
    const names = app.globalData.generatedNames || [];
    const userInput = app.globalData.userInput || {};
    
    this.setData({
      generatedNames: names,
      userInput: userInput
    });
    
    this.updateFavoriteStatus();
  },

  // 切换收藏状态
  toggleFavorite(e) {
    const index = e.currentTarget.dataset.index;
    const names = [...this.data.generatedNames];
    names[index].isFavorite = !names[index].isFavorite;
    
    this.setData({
      generatedNames: names
    });
    
    this.updateFavoriteStatus();
    
    // 保存到本地存储
    this.saveFavorites();
    
    // 显示提示
    wx.showToast({
      title: names[index].isFavorite ? '已收藏' : '已取消收藏',
      icon: 'success',
      duration: 1500
    });
  },

  // 复制名字
  copyName(e) {
    const name = e.currentTarget.dataset.name;
    
    // 复制到剪贴板
    wx.setClipboardData({
      data: name,
      success: () => {
        wx.showToast({
          title: '名字已复制',
          icon: 'success',
          duration: 1500
        });
      }
    });
  },

  // 重新生成名字
  regenerateNames() {
    wx.showModal({
      title: '确认重新生成',
      content: '确定要重新生成名字吗？当前结果将被替换。',
      success: (res) => {
        if (res.confirm) {
          // 返回首页重新生成
          wx.navigateBack();
        }
      }
    });
  },

  // 返回首页
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 更新收藏状态
  updateFavoriteStatus() {
    const favorites = this.data.generatedNames.filter(name => name.isFavorite);
    const hasFavorites = favorites.length > 0;
    const favoriteCount = favorites.length;
    
    this.setData({
      hasFavorites: hasFavorites,
      favoriteCount: favoriteCount
    });
  },

  // 保存收藏到本地存储
  saveFavorites() {
    const favorites = this.data.generatedNames.filter(name => name.isFavorite);
    try {
      wx.setStorageSync('favoriteNames', favorites);
    } catch (e) {
      console.error('保存收藏失败:', e);
    }
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '智能起名助手 - 为宝宝起个好名字',
      path: '/pages/index/index',
      imageUrl: '/images/share-image.png' // 需要添加分享图片
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '智能起名助手 - 为宝宝起个好名字',
      imageUrl: '/images/share-image.png' // 需要添加分享图片
    };
  }
});
